package cn.dankal.flyaudio.friend;

import android.content.Intent;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.jeremyliao.liveeventbus.LiveEventBus;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.common.bus.LiveDataBusConstants;
import cn.dankal.basiclib.util.JMessageToastUtils;
import cn.dankal.basiclib.util.SimpleTextChange;
import cn.dankal.basiclib.util.SpannableStringUtils;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.basiclib.widget.ClearEditText;
import cn.dankal.flyaudio.FlyApplication;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.ContractPersonAdapter;
import cn.dankal.flyaudio.adapter.ItemPickContractImgAdapter;
import cn.dankal.flyaudio.entity.Event;
import cn.dankal.flyaudio.entity.EventType;
import cn.dankal.flyaudio.entity.GroupEntity;
import cn.dankal.flyaudio.entity.PickContractPersonEntity;
import cn.dankal.flyaudio.friend.utils.pinyin.HanziToPinyin;
import cn.dankal.flyaudio.view.LetterNavView;
import cn.jpush.im.android.api.ContactManager;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.CreateGroupCallback;
import cn.jpush.im.android.api.callback.GetUserInfoListCallback;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;

public class PickContractPersonActivity extends BaseActivity {

    /**
     * 添加群组成员
     */
    public static final int TYPE_ADD_GROUP_MEMBERS = 1001;
    /**
     * 创建颧髎
     */
    public static final int TYPE_CREATE_GROUP = 1002;
    /**
     * 通过私聊加人创建群聊
     */
    public static final int TYPE_PRIVATE_CREATE_GROUP = 1004;
    /**
     * 删除群组成员
     */
    public static final int TYPE_DELETE_GROUP_MEMBERS = 1003;


    private RecyclerView friendView, mRvUser;
    private LetterNavView navView;
    private ImageView rightIcon;
    private TextView rightText;
    private TextView titleView;
    private View newFriendView;
    private View newFriendLineView;
    private View groupView;

    private TextView searchTextView;

    private ClearEditText searchEditText;

    private MultipleStatusView statusView;

    private ContractPersonAdapter adapter;
    private ItemPickContractImgAdapter itemPickContractImgAdapter;
    private List<GroupEntity> personEntities = new ArrayList<>();

    List<GroupEntity> groupEntities = new ArrayList<>();

    private int currentType = TYPE_CREATE_GROUP;

    private long groupId = 0;

    private String targetId = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_contract_person;
    }

    @Override
    protected void initComponents() {
        groupId = getIntent().getLongExtra(FlyApplication.GROUP_ID, 0);
        targetId = getIntent().getStringExtra(FlyApplication.TARGET_ID);
        currentType = getIntent().getIntExtra("type", TYPE_CREATE_GROUP);
        friendView = findViewById(R.id.rv_friend);
        rightIcon = findViewById(R.id.iv_friend_add);
        navView = findViewById(R.id.letter_container);
        mRvUser = findViewById(R.id.mRv_user);
        mRvUser.setVisibility(View.VISIBLE);
        initSearch();
        rightText = findViewById(R.id.tv_confirm);
        groupView = findViewById(R.id.rl_group_layout);
        newFriendView = findViewById(R.id.rl_new_friend_layout);
        newFriendLineView = findViewById(R.id.rl_new_friend_line);
        mRvUser = findViewById(R.id.mRv_user);
        itemPickContractImgAdapter = new ItemPickContractImgAdapter();
        groupView.setVisibility(View.GONE);
        newFriendLineView.setVisibility(View.GONE);
        newFriendView.setVisibility(View.GONE);
        titleView = findViewById(R.id.tv_title);
        rightIcon.setVisibility(View.GONE);
        rightText.setVisibility(View.VISIBLE);
        rightText.setEnabled(false);
        titleView.setText("选择联系人");
        findViewById(R.id.iv_onback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        friendView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ContractPersonAdapter(this, personEntities);
        adapter.setPickModel(ContractPersonAdapter.MODEL_PICK);
        friendView.setAdapter(adapter);
        mRvUser.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,
                false));
        mRvUser.setAdapter(itemPickContractImgAdapter);
        navView.setLetterChangeListener(new LetterNavView.LetterChangeListener() {
            @Override
            public void onTouchingLetterChanged(int index, String text) {
                int count = 0;
                for (int i = 0; i < index; i++) {
                    count++;
                    if (personEntities.isEmpty()) {
                        return;
                    }
                    count += personEntities.get(i).getChildren().size();
                }
                if (count != -1) {
                    friendView.scrollToPosition(count);
                    LinearLayoutManager mLayoutManager =
                            (LinearLayoutManager) friendView.getLayoutManager();
                    mLayoutManager.scrollToPositionWithOffset(count, 0);
                }
            }
        });
        adapter.setOnItemSelectListener(new ContractPersonAdapter.OnItemSelectListener() {
            @Override
            public void onSelect(List<UserInfo> userInfos) {
                itemPickContractImgAdapter.updateData(userInfos);
                if (userInfos.isEmpty()) {
                    rightText.setEnabled(false);
                    rightText.setClickable(false);
                } else {
                    rightText.setEnabled(true);
                    rightText.setClickable(true);
                }
            }
        });
        if (currentType == TYPE_DELETE_GROUP_MEMBERS) {
            final Conversation conv = JMessageClient.getGroupConversation(groupId);
            GroupInfo mGroupInfo = (GroupInfo) conv.getTargetInfo();
            if (TextUtils.isEmpty(mGroupInfo.getGroupName())) {
                ToastUtils.showShort("无效群组");
                finish();
            }
            handleFriend(mGroupInfo.getGroupMembers());
        } else {
            ContactManager.getFriendList(new GetUserInfoListCallback() {
                @Override
                public void gotResult(int i, String s, List<UserInfo> list) {
                    handleFriend(list);
                }
            });
        }


        rightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> username = new ArrayList<>();
                if (currentType == TYPE_CREATE_GROUP) {
                    StringBuilder groupName = new StringBuilder();
                    groupName.append(JMessageClient.getMyInfo().getUserName());
                    groupName.append(",");
                    for (UserInfo userInfo : adapter.getPickMember()) {
                        username.add(userInfo.getUserName());
                        groupName.append(userInfo.getUserName());
                        groupName.append(",");
                    }
                    PickContractPersonEntity entity = new PickContractPersonEntity();
                    entity.setUserInfos(username);
                    doCreateGroup(entity);
                } else if (currentType == TYPE_PRIVATE_CREATE_GROUP) {
                    StringBuilder groupName = new StringBuilder();
                    groupName.append(JMessageClient.getMyInfo().getUserName());
                    groupName.append(",");
                    for (UserInfo userInfo : adapter.getPickMember()) {
                        username.add(userInfo.getUserName());
                        groupName.append(userInfo.getUserName());
                        groupName.append(",");
                    }
                    username.add(targetId);
                    PickContractPersonEntity entity = new PickContractPersonEntity();
                    entity.setUserInfos(username);
                    doCreateGroup(entity);
                } else if (currentType == TYPE_ADD_GROUP_MEMBERS) {
                    StringBuilder groupName = new StringBuilder();
                    for (UserInfo userInfo : adapter.getPickMember()) {
                        username.add(userInfo.getUserName());
                        groupName.append(userInfo.getUserName());
                        groupName.append(",");
                    }
                    PickContractPersonEntity entity = new PickContractPersonEntity();
                    entity.setUserInfos(username);
                    addGroupMembers(entity);
                } else if (currentType == TYPE_DELETE_GROUP_MEMBERS) {
                    StringBuilder groupName = new StringBuilder();
                    for (UserInfo userInfo : adapter.getPickMember()) {
                        username.add(userInfo.getUserName());
                        groupName.append(userInfo.getUserName());
                        groupName.append(",");
                    }
                    PickContractPersonEntity entity = new PickContractPersonEntity();
                    entity.setUserInfos(username);
                    deleteGroupMembers(entity);
                }

//                Intent intent = new Intent();
//                intent.putExtra("users",entity);
//                setResult(RESULT_OK,intent);
//                finish();
//                LiveEventBus.get("pick_contract_person", PickContractPersonEntity.class).postValue(entity);
            }
        });
    }

    private void addGroupMembers(PickContractPersonEntity pickContractPersonEntity) {
        showLoadingDialog();
        List<String> username = pickContractPersonEntity.getUserInfos();
        StringBuilder groupName = new StringBuilder();
        groupName.append(JMessageClient.getMyInfo().getUserName());
        groupName.append(",");
        for (String userInfo : username) {
            groupName.append(userInfo);
            groupName.append(",");
        }
        if (groupName.length() > 10) {
            groupName.delete(10, groupName.length());
        }
        JMessageClient.addGroupMembers(groupId, username, new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                if (i == 0) {
                    ToastUtils.showShort("添加成功");
                    dismissLoadingDialog();
                    Conversation groupConversation = JMessageClient.getGroupConversation(groupId);
                    if (groupConversation == null) {
                        groupConversation = Conversation.createGroupConversation(groupId);
                        EventBus.getDefault().post(new Event.Builder()
                                .setType(EventType.createConversation)
                                .setConversation(groupConversation)
                                .build());
                    }
                    LiveEventBus.get(LiveDataBusConstants.UPDATE_GROUP_MEMBERS_INFO, String.class).post("");
                    finish();
                } else {
                    dismissLoadingDialog();
                    if (s.contains("added")) {
                        ToastUtils.showShort("选择的成员已在群组中，请重新选择");
                    } else {
                        JMessageToastUtils.errorToast(i);
                    }
                }
            }
        });
    }

    private void deleteGroupMembers(PickContractPersonEntity pickContractPersonEntity) {
        showLoadingDialog();
        List<String> username = pickContractPersonEntity.getUserInfos();
        StringBuilder groupName = new StringBuilder();
        groupName.append(JMessageClient.getMyInfo().getUserName());
        groupName.append(",");
        for (String userInfo : username) {
            groupName.append(userInfo);
            groupName.append(",");
        }
        if (groupName.length() > 10) {
            groupName.delete(10, groupName.length());
        }
        JMessageClient.removeGroupMembers(groupId, username, new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                dismissLoadingDialog();
                if (i == 0) {
                    ToastUtils.showShort("删除成功");
                    Conversation groupConversation = JMessageClient.getGroupConversation(groupId);
                    if (groupConversation == null) {
                        groupConversation = Conversation.createGroupConversation(groupId);
                        EventBus.getDefault().post(new Event.Builder()
                                .setType(EventType.deleteConversation)
                                .setConversation(groupConversation)
                                .build());
                    }
                    LiveEventBus.get(LiveDataBusConstants.UPDATE_GROUP_MEMBERS_INFO, String.class).post("");
                    finish();
                } else {
                    JMessageToastUtils.errorToast(i);
                }
            }
        });
    }

    private void doCreateGroup(PickContractPersonEntity pickContractPersonEntity) {
        showLoadingDialog();
        List<String> username = pickContractPersonEntity.getUserInfos();
        StringBuilder groupName = new StringBuilder();
        groupName.append(JMessageClient.getMyInfo().getUserName());
        groupName.append(",");
        for (String userInfo : username) {
            groupName.append(userInfo);
            groupName.append(",");
        }
        if (groupName.length() > 10) {
            groupName.delete(10, groupName.length());
        }
        JMessageClient.createPublicGroup(groupName.toString(), "没有什么", new CreateGroupCallback() {
            @Override
            public void gotResult(int resopnseCode, String s, long groupId) {
                if (resopnseCode == 0) {
                    JMessageClient.addGroupMembers(groupId, FlyApplication.JPUSH_KEY, username, new BasicCallback() {
                        @Override
                        public void gotResult(int i, String s) {
                            dismissLoadingDialog();
                            Conversation groupConversation = JMessageClient.getGroupConversation(groupId);
                            if (groupConversation == null) {
                                groupConversation = Conversation.createGroupConversation(groupId);
                                EventBus.getDefault().post(new Event.Builder()
                                        .setType(EventType.createConversation)
                                        .setConversation(groupConversation)
                                        .build());
                            }

                            Intent intent = new Intent(PickContractPersonActivity.this, ChatActivity.class);
                            intent.putExtra(FlyApplication.CONV_TITLE, groupName.toString());
                            intent.putExtra(FlyApplication.GROUP_ID, groupId);
                            startActivity(intent);
                            finish();
                        }
                    });
                } else {
                    dismissLoadingDialog();
                    ToastUtils.showShort("创建群组失败:" + s);
                }
            }
        });
    }

    private List<UserInfo> friendList = new ArrayList<>();

    private void initSearch() {
        statusView = findViewById(R.id.multiple_status_view);
        searchTextView = findViewById(R.id.tv_search);
        searchEditText = findViewById(R.id.et_search);
        searchEditText.setOnSearchListener(new ClearEditText.OnSearchListener() {
            @Override
            public void doSearch(String keyword) {
                if (TextUtils.isEmpty(keyword)) return;
                mDoSearch(keyword);
            }
        });
        searchTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = searchEditText.getText().toString();
                if (TextUtils.isEmpty(key)) return;
                mDoSearch(key);
            }
        });
        searchEditText.addTextChangedListener(new SimpleTextChange() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                super.onTextChanged(s, start, before, count);
                if (TextUtils.isEmpty(s)) {
                    if(currentType==TYPE_DELETE_GROUP_MEMBERS){
                        final Conversation conv = JMessageClient.getGroupConversation(groupId);
                        GroupInfo mGroupInfo = (GroupInfo) conv.getTargetInfo();
                        if (TextUtils.isEmpty(mGroupInfo.getGroupName())) {
                            ToastUtils.showShort("无效群组");
                            finish();
                        }
                        handleFriend(mGroupInfo.getGroupMembers());
                    }else{
                        ContactManager.getFriendList(new GetUserInfoListCallback() {
                            @Override
                            public void gotResult(int i, String s, List<UserInfo> list) {
                                handleFriend(list);
                            }
                        });
                    }
                }
            }
        });
        statusView.showContent();
    }

    private void mDoSearch(String key) {
        List<UserInfo> searResult = new ArrayList<>();
        for (UserInfo userInfo : friendList) {
            ArrayList<HanziToPinyin.Token> tokens = HanziToPinyin.getInstance()
                    .get(userInfo.getNickname());
            StringBuilder sb = new StringBuilder();
            if (tokens != null && tokens.size() > 0) {
                for (HanziToPinyin.Token token : tokens) {
                    if (token.type == HanziToPinyin.Token.PINYIN) {
                        sb.append(token.target);
                    } else {
                        sb.append(token.source);
                    }
                }
            }
            if (sb.toString().contains(key) || userInfo.getNickname().contains(key)) {
                searResult.add(userInfo);
            }
        }
        if (searResult.isEmpty()) {
            SpannableStringBuilder s =
                    SpannableStringUtils.getBuilder(key).setForegroundColor(getResources().getColor(R.color.color_0085B4)).create();

            statusView.showEmpty("- 没有找到“"+s+"”相关结果 -");

            findViewById(R.id.status_hint_content_1).setVisibility(View.GONE);
        }else {
            statusView.showContent();
            findViewById(R.id.status_hint_content_1).setVisibility(View.VISIBLE);
            handleFriend(searResult);
//            adapter.setNewData(searResult, true);
//            friendView.setAdapter(searchUserAdapter);
        }
    }


    private void handleFriend(List<UserInfo> list) {
        friendList.clear();
        for (UserInfo userInfo : list) {
            if (userInfo.getNickname().equals(JMessageClient.getMyInfo().getNickname())) {
                list.remove(userInfo);
                break;
            }
        }
        for (UserInfo userInfo : list) {
            //将正在聊天的好友移除，自动添加到群聊中
            if (currentType == TYPE_PRIVATE_CREATE_GROUP) {
                if (TextUtils.equals(targetId, userInfo.getUserName())) {
                    list.remove(userInfo);
                    break;
                }
            }
        }
        friendList.addAll(list);
        groupEntities.clear();
        for (UserInfo userInfo : list) {
            String letter = getLetter(userInfo.getNickname());
            if (!checkGroupSave(letter)) {
                GroupEntity groupEntity = new GroupEntity();
                groupEntity.setHeader(letter);
                groupEntities.add(groupEntity);
            }
            GroupEntity groupEntity = getGroupByLetter(letter);
            if (groupEntity != null) {
                List<UserInfo> userInfos = groupEntity.getChildren();
                userInfos.add(userInfo);
                groupEntity.setChildren(userInfos);
            }
        }
        adapter.setNewData(groupEntities);
    }

    private boolean checkGroupSave(String letter) {
        for (GroupEntity entity : groupEntities) {
            if (entity.getHeader().contains(letter)) {
                return true;
            }
        }
        return false;
    }

    private GroupEntity getGroupByLetter(String letter) {
        for (GroupEntity entity : groupEntities) {
            if (entity.getHeader().contains(letter)) {
                return entity;
            }
        }
        return null;
    }

    private String getLetter(String name) {
        String letter;
        ArrayList<HanziToPinyin.Token> tokens = HanziToPinyin.getInstance()
                .get(name);
        StringBuilder sb = new StringBuilder();
        if (tokens != null && tokens.size() > 0) {
            for (HanziToPinyin.Token token : tokens) {
                if (token.type == HanziToPinyin.Token.PINYIN) {
                    sb.append(token.target);
                } else {
                    sb.append(token.source);
                }
            }
        }
        String sortString = sb.toString().substring(0, 1).toUpperCase();
        if (sortString.matches("[A-Z]")) {
            letter = sortString.toUpperCase();
        } else {
            letter = "#";
        }
        return letter;
    }

}
